package org.mokusakura.persistence.Util;

/**
 * @author MokuSakura
 */
public class IDWorker {
    private final long computerId;
    private long sequence;
    private long lastTime;

    public IDWorker(long computerId) {
        this.computerId = computerId;
    }

    public long getComputerId() {
        return computerId;
    }

    public synchronized long nextId() {
        long res = System.currentTimeMillis();

        if (lastTime == res) {
            sequence =
                    (sequence + 1) & 0b1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1110_1111_1111_1111L;
            //0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0001_0000_0000_0000,4096
            //1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1110_1111_1111_1111
            if (sequence == 0) {
                while (res <= lastTime) {
                    res = System.currentTimeMillis();
                }
            }
        } else {
            sequence = 0;
        }
        lastTime = res;
        res = (res << 22) | (computerId << 12) | sequence;
        return res;
    }

}
